import logging
logging.basicConfig(level=logging.DEBUG)
from flask import Flask, jsonify
from flask_socketio import SocketIO
from models.database import init_db
from routes.auth import auth_bp
from routes.video import video_bp
from routes.device import device_bp
from routes.message import message_bp
from routes.pages import pages_bp
from routes.tv_control import tv_control_bp
from routes.realtime_control import realtime_bp
from services.socket_service import SocketService
from utils.config import config


def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    app.secret_key = config.SECRET_KEY
    app.config['DEBUG'] = config.DEBUG
    
    # 初始化数据库
    init_db()
    
    # 注册蓝图
    app.register_blueprint(auth_bp)
    app.register_blueprint(video_bp)
    app.register_blueprint(device_bp)
    app.register_blueprint(message_bp)
    app.register_blueprint(pages_bp)
    app.register_blueprint(tv_control_bp)
    app.register_blueprint(realtime_bp)
    
    return app

def create_socketio(app):
    """创建SocketIO实例"""
    socketio = SocketIO(
        app, 
        cors_allowed_origins="*", 
        async_mode='threading',
        logger=True,
        engineio_logger=True,
        ping_timeout=60,
        ping_interval=25
    )
    
    # 初始化Socket.IO服务
    # socket_service = SocketService(socketio)
    
    return socketio

if __name__ == '__main__':
    app = create_app()
    socketio = create_socketio(app)
    
    # 添加错误处理
    @app.errorhandler(500)
    def internal_error(error):
        return jsonify({
            'success': False,
            'error': '服务器内部错误',
            'message': '请稍后重试'
        }), 500
    
    @app.errorhandler(404)
    def not_found_error(error):
        return jsonify({
            'success': False,
            'error': '页面不存在',
            'message': '请求的资源不存在'
        }), 404
    
    # 启动应用
    try:
        socketio.run(app, debug=config.DEBUG, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=True)
    except Exception as e:
        print(f"启动服务器失败: {e}")
        import traceback
        traceback.print_exc()
